<?php
// +----------------------------------------------------------------------
// | my
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\we\model;

use think\Model;

class WeFansBuy extends Model
{
    protected $insert = ['status'=>1]; 
    
    /**
     * 获取微信配置信息，需要缓存
     */
    public function info($openid,$field=true){
      
      if (is_numeric($openid)){
        $map['id']=$openid;
      }else{
        $map['openid']=$openid;
      }
      $fans = $this->field($field)->where($map)->find();
     
      return  $fans;
    }

     public function infoForFans($openid,$field=true){
      $fans=$this->info($openid,$field=true);
      if (!$fans) return false;
      $printer=model('printer/PrinterFans')->info($fans['openid'],'balance');

      $message="粉丝信息";
      $message.="\nID：".$fans['id'];
      $message.="\n昵称：".$fans['nickname'];
      if($printer) $message.="\n打印余额：".$printer['balance'];
      return  ['fans'=>$fans,'message'=>$message];
    }

    public function infoForFansByOrder($data){
     $fans = $this->infoForFans($data['before']);
     if (!$fans) return ['message'=>'粉丝不存在，请核对粉丝ID'];
     return ['message'=>$fans['message']]; //空尾巴查询
    }

     public function getAdmins($appid){
      $map['appid']=$appid;
      $map['userid']=['NEQ',''];
     
      $admins=$this->where($map)->select();

      
      return  $admins;
    }




    public function editData($data){

      
      if (isset($data['id'])){
         $res = $this->allowField(true)->where('id',$data['id'])->update($data);
      }else{
         $res = $this->allowField(true)->data($data)->save();
      }

      return $res;
    }

    public function buy($data){
  
        if(strstr($data['before'],'+')){
            $fans_id= substr($data['before'],0,strrpos($data['before'],'+'));
            $customer=str_replace($fans_id.'+','',$data['before']);
        }
        $fans=[];
        if ($fans_id){
          $fans=model('we/WeFans')->info($fans_id);
          if (!$fans)return ['message'=>$fans_id.'号粉丝不存在'];
        }

        if(strstr($data['back'],'++')){
            $desk = substr($data['back'],0,strrpos($data['back'],'++'));
            $price=str_replace($desk.'++','',$data['back']);
          }else{
            $desk = substr($data['back'],0,strrpos($data['back'],'+'));
            $price=str_replace($desk.'+','',$data['back']);
        }

        //数据有效性验证
        if (!$desk ) return ['message'=>'桌号没有输入'];
        if (!$price) return ['message'=>'消费金额没有输入'];
          
        $buy=[];

         
         //todo 防止重复录入
         $map['aid']=$data['aid'];
         $map['appid']=$data['appid'];
         if ($fans) $map['openid']=$fans['openid'];
         $map['desk']=$desk;
         $map['price']=$price;
         $have=$this->where($map)->where('create_time>='.(time()-600))->find();
         if ($have)return '系统检测到这条重复录入，请检查！';

        //本次服务员
        if (isset($data['fans']['admin_info']['shopid'])){
        $desk_qrcode=db('WeSceneQrcode')->where('shopid',$data['fans']['admin_info']['shopid'])->where('code','DESK'.$desk)->find();
        if(isset($desk_qrcode['admin']))$buy['this_admin']=$desk_qrcode['admin'];
        }
        

        if ($fans){

               //积星
              if($fans and strstr($data['back'],'++')){
                // $score_message=model('we/WeFansCfo')->cfoScore($fans,1,$data);
                // if ($score_message)$buy['score']=1;
              
               $qrcode['appid']=$data['appid']; 
               $qrcode['aid']=$data['aid']; 
               $qrcode['before']='积星' ;
               $qrcode['fans']['nickname']=$data['fans']['nickname'];
               $qrcode['fans']['openid']=$data['fans']['openid'];

               $score_qrcode=model('we/WeSceneQrcode')-> getQrcode0($qrcode,'2592000','0',$customer);
               $error= custom_message($fans['openid'],"【重要】恭喜您获取积星资格，点击".$score_qrcode."长按识别二维码自动积星，分享同桌朋友朋友也可以积星，集齐6星换烤鱼，8星换焖锅，不用谢，我是雷锋！");
              }

              //分销提成
              // if($fans['subscribe_openid'] and $data['options']['tui_reward']){
               
              //   $father_fans=model('we/WeFans')->info($fans['subscribe_openid']);
              //   $reward=$data['options']['tui_reward']*$price;
              //   $amount_message=model('we/WeFansCfo')->cfoAmount($father_fans,$reward,$data,'推广消费',$father_fans['nickname'].'您的好友'.$fans['nickname'].'消费'.$price.'元，您获得了'.$reward.'元奖励，已经存入您的会员账户下，请查收！');
              //   if ($amount_message){
              //     $buy['reward']=$reward;
              //     $buy['reward_openid']=$fans['subscribe_openid'];
              //   }
              // }
              
              //老顾客，上一次有效消费
               $last_admin=$this->where('openid',$fans['openid'])->where('status=1')->order('create_time desc')->value('this_admin');
               $buy['last_admin']=$last_admin;
              
         }

         $buy['aid']=$data['aid'];
         $buy['appid']=$data['appid'];
         $buy['shopid']=$data['fans']['admin_info']['shopid'];
         if ($fans) $buy['openid']=$fans['openid'];
         $buy['admin']=$data['admin'];
         $buy['desk']=$desk;
         $buy['customer']=$customer;
         $buy['price']=$price;
         $res=$this->editData($buy);
         $shop=[];
         if($buy['shopid'])$shop=model('admin/AdminShop')->info($buy['shopid']);




         if ($res) {
          $message='';
          if ($fans )$message.=$fans['id'].'号顾客'.$fans['nickname'].'带';
          $message.=$customer.'人在'.$shop['title'].$desk.'号桌消费'.$price.'元，录入成功'.(isset($buy['score'])?'，已为顾客积星！':'');
         }else{
           $message="失败";
         }
         return $message;
    }


     public function buyBoss($map=[]){
      $map['shopid']=3;
      $map['status']=['egt',0];
      $field="count(id) as desk_total,sum(customer) as customer_total,sum(price) as price_total";
     
      $boss=$this->field($field)->where($map)->whereTime('create_time','today')->find();
     
      $message='司门口：';
      $message.='桌数'.$boss['desk_total'];
      $message.='，顾客数'.$boss['customer_total'];
      $message.='，营业额'.$boss['price_total'];

      
      return  $message;
    }

    
  
    

    
}